﻿using System;
using System.Collections.Generic;
using System.Linq;
using TLang.Values;

namespace TLang.Ast
{
    public class CondNode : Node
    {
        private readonly List<Tuple<Node, Node>> _elements;

        public CondNode(List<Tuple<Node, Node>> elements, String file, int start, int end, int line, int col) : base(file, start, end, line, col)
        {
            this._elements = elements;
        }

        public override Value Interp(Scope s)
        {
            for (int i = 0; i < this._elements.Count; i++)
            {
                var tuple = this._elements[i];
                if ((tuple.Item1 is NameNode nameNode && nameNode.Id == Constants.ElseKeyword)
                        || (tuple.Item1 is KeywordNode keywordNode && keywordNode.Id == Constants.ElseKeyword))
                {
                    Node valueNode = tuple.Item2;
                    return valueNode.Interp(s);
                }
                Node testNode = tuple.Item1;
                Value testValue = testNode.Interp(s);
                if (testValue is BoolValue bv)
                {
                    if (bv.Value)
                    {
                        Node valueNode = tuple.Item2;
                        return valueNode.Interp(s);
                    }
                }
                else
                {
                    throw new GeneralError(testNode, testNode.ToString() + " must be bool type");
                }
            }
            return VoidValue.Void;
        }

        public override string ToString()
        {
            return $"({Constants.CondKeyword} {string.Join(" ", this._elements.Select(a => "[" + a.Item1.ToString() + " " + a.Item2.ToString() + "]"))})";
        }
    }
}
